#include "bsp_init.h"
#include "time.h"
#include "adc.h"
#include "dac.h"
#include "gpio.h"
#include "foc.h"

extern ADC_HandleTypeDef hadc1;
extern ADC_HandleTypeDef hadc2;
extern DAC_HandleTypeDef hdac;
extern TIM_HandleTypeDef htim1;
extern TIM_HandleTypeDef htim2;
extern TIM_HandleTypeDef htim3;
extern TIM_HandleTypeDef htim7;
extern UART_HandleTypeDef huart1;

const uint16_t sine_wave[32] = 
{
	2448,2832,3186,3496,3751,3940,4057,4095,4057,3940,
	3751,3496,3186,2832,2448,2048,1648,1264,910,600,345,
	156,39,0,39,156,345,600,910,1264,1648,2048
};

//peripheral motor dirver system needed init
uint8_t _bsp_init(void)
{
    /*******************  timer *************************/
    //timer start 
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_3);
    HAL_TIMEx_PWMN_Start(&htim1,TIM_CHANNEL_1);
	HAL_TIMEx_PWMN_Start(&htim1,TIM_CHANNEL_2);
	HAL_TIMEx_PWMN_Start(&htim1,TIM_CHANNEL_3);
    //no output at first time
    __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1, 0);
    __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_2, 0);
    __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3, 0);
    //tim1 ch4 cc out at the cent of pwm to trigger adc 
    //which get uvw current
    // HAL_TIM_PWM_Start_IT(&htim1,TIM_CHANNEL_4);
	HAL_TIM_Base_Start(&htim1);

    HAL_TIM_PWM_Stop_IT(&htim1,TIM_CHANNEL_4);
	HAL_TIM_Base_Stop_IT(&htim1);
    //tim2 in encoder mode to get encoder counter
    HAL_TIM_Base_Start(&htim2);
    HAL_TIM_Encoder_Start(&htim2, TIM_CHANNEL_1|TIM_CHANNEL_2);
    __HAL_TIM_SET_COUNTER(&htim3,ENCODER_ZERO);

    //HALL TIMER START
    HAL_TIM_Base_Start(&htim3);

    //dac trigger timmer
    HAL_TIM_Base_Start(&htim7);  

    //dac start output sine wave for test only, need to stop dma when regulation worked 
    HAL_DAC_Start_DMA(&hdac,DAC_CHANNEL_1, (uint32_t *)sine_wave, 32, DAC_ALIGN_12B_R);
    HAL_DAC_Start_DMA(&hdac,DAC_CHANNEL_2, (uint32_t *)sine_wave, 32, DAC_ALIGN_12B_R);

    
    foc_test_init();

    return 0;
}




